package com.fit.utils.ee;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Cookie工具类
 * @author hcl
 *
 */
public class CookieUtil {

	private static Logger log = LoggerFactory.getLogger(CookieUtil.class);
	
	private static String encoding = "UTF-8";
	
	/**
	 * 设置 Cookie（生成时间为30天）
	 * @param response 响应对象
	 * @param name 名称
	 * @param value 值
	 */
	public static void setCookie(HttpServletResponse response, String name, String value) {
		setCookie(response, name, value, "/" , 2592000);//30天
	}
	
	/**
	 * 设置 Cookie（生成时间为30天）
	 * @param response 响应对象
	 * @param name 名称
	 * @param value 值
	 * @param path 存储域
	 */
	public static void setCookie(HttpServletResponse response, String name, String value,String path) {
		setCookie(response, name, value, path , 2592000);//30天
	}
	
	/**
	 * 设置 Cookie
	 * @param response 响应对象
	 * @param name 名称
	 * @param value 值
	 * @param path 存储域
	 * @param maxAge 生存时间（单位秒）
	 */
	public static void setCookie(HttpServletResponse response, String name, String value,String path, int maxAge) {
		try {
			Cookie cookie = new Cookie(name, null);
			cookie.setPath(path);
			cookie.setMaxAge(maxAge);
			cookie.setValue(URLEncoder.encode(value, encoding));
			response.addCookie(cookie);
		} catch (UnsupportedEncodingException e) {
			log.error("设置cookie异常", e);
		}
		
	}
	/**
	 * 获得指定Cookie的值
	 * @param name 名称
	 * @return 值
	 */
	public static String getCookie(HttpServletRequest request, String name) {
		return getCookie(request, null, name, false);
	}
	/**
	 * 获得指定Cookie的值，并删除。
	 * @param name 名称
	 * @return 值
	 */
	public static String getCookie(HttpServletRequest request, HttpServletResponse response, String name) {
		return getCookie(request, response, name, true);
	}
	/**
	 * 获得指定Cookie的值
	 * @param request 请求对象
	 * @param response 响应对象
	 * @param name 名字
	 * @param isRemove 是否移除
	 * @return 值
	 */
	public static String getCookie(HttpServletRequest request, HttpServletResponse response, String name, boolean isRemove) {
		String value = null;
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals(name)) {
					try {
						value = URLDecoder.decode(cookie.getValue(), encoding);
						if (isRemove) {
							cookie.setMaxAge(0);
							response.addCookie(cookie);
						}
					} catch (UnsupportedEncodingException e) {
						log.error("获取cookie异常", e);
					}
				}
			}
		}
		return value;
	}
}
